package com.zhaorujie.rpc.core.remoting.netty.codec;

import com.zhaorujie.rpc.core.remoting.common.Constant;
import com.zhaorujie.rpc.core.serialize.RpcSerialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author 赵汝杰
 * @version v1.0
 * @description NettyEncoder
 * @date 2024/3/5
 **/
public class NettyEncoder extends MessageToByteEncoder<Object> {

    private final Class<?> genericClass;
    private final RpcSerialize rpcSerialize;

    public NettyEncoder(Class<?> genericClass, RpcSerialize rpcSerialize) {
        this.genericClass = genericClass;
        this.rpcSerialize = rpcSerialize;
    }



    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object in, ByteBuf out) throws Exception {
        byte[] bytes = rpcSerialize.serialize(in);
        out.writeByte(Constant.MAGIC);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
    }
}
